/**
 * Node 类用来表示节点
 * element 用来保存节点上的数据
 * next 用来保存指向下一个节点的链接
 */
const Node = function (element) {
  this.element = element
  this.next = null
}

class LinkedList {
  constructor() {
    this.head = new Node('head')
  }

  // 查找节点
  find (item) {
    let curNode = this.head

    while (curNode.element !== item) {
      curNode = curNode.next
    }

    return curNode
  }

  // 查找前一个节点
  findPrev (item) {
    if (item === 'head') throw new Error('now is head!')

    let curNode = this.head
    while (curNode.next && curNode.next.element !== item) {
      curNode = curNode.next
    }

    return curNode
  }

  // 插入新节点
  insert (newElement, item) {
    let newNode = new Node(newElement)
    let curNode = this.find(item)
    newNode.next = curNode.next
    curNode.next = newNode
  }

  // 删除一个节点
  remove (item) {
    let prevNode = this.findPrev(item)
    if (prevNode.next !== null) {
      prevNode.next = prevNode.next.next
    }
  }

  // 显示链表中的元素
  display () {
    let curNode = this.head

    while (curNode.next != null) {
      console.log(curNode.next.element)
      curNode = curNode.next
    }
  }
}
